<template>
  <a-spin :spinning="confirmLoading">
    <!-- 临时额度设置区域 -->
    <a-alert type="info" message="提示：临近时间节点3分钟左右请勿操作相关配置" show-icon> </a-alert>

    <j-form-container :disabled="formDisabled" style="margin-top: 20px">
      <a-form-model ref="formRow" :model="modelObj" slot="detail">
        <a-row>
          <!-- 0:关，1开   1是0否 -->
          <a-col :span="4">
            <a-form-model-item
              label="临时额度"
              prop="izOpenTemporary"
              :labelCol="labelColS"
              :wrapperCol="wrapperColS"
            >
              <a-switch
                checked-children="开"
                un-checked-children="关"
                :checked="modelObj.izOpenTemporary == '1' ? true : false"
                @change="onChangeOpenTemporary"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="4" v-if="modelObj.izOpenTemporary == '1'" style="margin-left: 3.8%;">
            <a-form-model-item
              label="是否循环"
              prop="izCycleTemporary"
              :labelCol="labelColS"
              :wrapperCol="wrapperColS"
            >
              <!-- <a-radio-group :options="loopOption" v-model="model.loop" /> -->
              <a-switch
                checked-children="开"
                un-checked-children="关"
                :checked="modelObj.izCycleTemporary == '1' ? true : false"
                @change="onChangeCycleTemporary"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <a-form-model
        ref="form"
        :model="model"
        :rules="validatorRules"
        slot="detail"
        v-if="modelObj.izOpenTemporary == '1'"
      >      
      <a-row>
        <a-form-model-item
            label="额度配置"          
            :labelCol="labelColS"
            :wrapperCol="wrapperColS"
            prop="temporaryType"
          >
          <j-dict-select-tag
          v-model="model.temporaryType"
          type="radio"
          dictCode="settlement_org_config_temporary_type"
          :disabled="disabledOperation"
        />
          </a-form-model-item>
      </a-row>
        
        <a-row v-if="model.temporaryType == 1">
          <a-form-model-item
            label="临时额度天数"
            required
            :labelCol="labelColS"
            :wrapperCol="wrapperColS"
            prop="temporaryDayNum"
          >
            <a-input-number
              :disabled="disabledOperation"
              id="inputNumber"
              v-model="model.temporaryDayNum"
            />
            天
          </a-form-model-item>
        </a-row>
        <a-row v-if="model.temporaryType == 2">
          <a-col :span="12">
            <a-form-model-item
              label="临时额度天数"
              required
              :labelCol="labelColS"
              :wrapperCol="wrapperColS"
              prop="temporaryDayNum"
            >
              <a-input-number
                :disabled="disabledOperation"
                id="inputNumber"
                v-model="model.temporaryDayNum"
              />
              天
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="临时额度"
              required
              :labelCol="labelColS"
              :wrapperCol="wrapperColS"
              prop="temporaryBalance"
            >
              <a-input-number :disabled="disabledOperation" id="inputNumber" v-model="model.temporaryBalance" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row style="display: flex; align-items: center">
          <a-col :span="12">
            <a-form-model-item
              label="开始时间"
              required
              :label-col="{ xs: { span: 24 }, sm: { span: 7 } }"
              :wrapperCol="wrapperCol"
              prop="beginTime"
            >
              <j-date
                placeholder="请选择开始时间"
                v-model="model.beginTime"
                :show-time="true"
                :disabled-date="disabledStartDate"
                date-format="YYYY-MM-DD HH:mm:ss"
                :show-today="false"
                :disabled="disabledOperation"
                @change="beginTimeChange"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" style="display: inline-flex; align-items: center">
            <a-form-model-item
              label="预计结束时间"
              :labelCol="labelColS"
              :wrapperCol="wrapperColS"
              prop="endtime"
              style="width: 100%"
            >
              <span class="ant-form-text">{{ endtime }}</span>
            </a-form-model-item>
            <a-button
              style="float: right"
              type="primary"
              :disabled="disabledOperation"
              :loading="saveLoading"
              @click="saveSettlementOrgConfig">保存</a-button>
          </a-col>
          <!-- <a-col :span="4" class="save">
            <a-button
              style="float: right"
              type="primary"
              :disabled="disabledOperation == true || disabledConfig == true ? true : false"
              :loading="saveLoading"
              @click="saveSettlementOrgConfig"
              >保存</a-button >
           
          </a-col> -->
        </a-row>

        <!-- <a-row style="float: right">
          <a-button type="primary" :disabled="disabledConfig" :loading="saveLoading" @click="saveSettlementOrgConfig">保存</a-button>
        </a-row> -->
      </a-form-model>
    </j-form-container>
    <!-- 临时额度设置区域 -->
    <a-table
      ref="table"
      size="middle"
      :scroll="{ x: true }"
      bordered
      rowKey="id"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="ipagination"
      :loading="loading"
      class="j-table-force-nowrap"
      style="margin-top: 30px"
    >
      <template slot="htmlSlot" slot-scope="text">
        <div v-html="text"></div>
      </template>
    </a-table>
  </a-spin>
</template>

<script>
import moment from 'moment'
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'

export default {
  name: 'BaseLineConfigForm',
  components: {},
  mixins: [mixinDevice],
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      modelObj: {
        izOpenTemporary: '0', //临时额度开关
        izCycleTemporary: '0', //临时额度循环开关
      },
      model: {
        id: '',
        temporaryDayNum: null,
        beginTime: null,
        endtime: '',
        temporaryType: 1,
        temporaryBalance:null,
      },
      initBeginTime: '',
      oldModel: {},
      dataSource: [],
      columns: [
        {
          title: '临时额度天数',
          dataIndex: 'temporaryDayNum',
          align: 'center',
        },
        {
          title: '临时额度',
          dataIndex: 'temporaryBalance',
          align: 'center',
        },
        {
          title: '开始时间',
          dataIndex: 'beginTime',
          align: 'center',
        },
        {
          title: '预计结束时间',
          dataIndex: 'endTime',
          align: 'center',
        },
        {
          title: '实际结束时间',
          dataIndex: 'realEndTime',
          align: 'center',
        },
        {
          title: '创建人',
          dataIndex: 'createBy',
          align: 'center',
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          align: 'center',
        },
      ],
      ipagination: {
        current: 1,
        pageSize: 20,
        pageSizeOptions: ['10', '20', '30', '50', '100'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      disabledConfig: true,
      disabledOperation: false,
      saveLoading: false,
      /* table加载状态 */
      loading: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 9 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
      labelColS: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
      wrapperColS: {
        xs: { span: 24 },
        sm: { span: 11 },
      },
      confirmLoading: false,
      validatorRules: {
        temporaryDayNum: [
          { required: true, message: '请输入临时额度天数' },
          { pattern: /^[1-9]\d*$/, message: '请输入零以上的正整数' },
        ],
        beginTime: [{ required: true, message: '请选择开始日期' }, { validator: this.validateBeginTime }],
        // temporaryBalance: [{ required: true, message: '请输入临时额度' }, { validator: this.validateTemporaryMoney }],
        temporaryBalance: [{ required: true, message: '请输入临时额度' },{ pattern:/^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '临时额度不能小于等于0' },]
      },
      url: {
        queryById: '/finance/baseSettlementOrgConfig/queryById', //结算组织配置-通过id查询
        editCycleStatus: '/finance/baseSettlementOrgConfig/editCycleStatus', //结算组织配置-编辑循环状态
        edit: '/finance/baseSettlementOrgConfig/edit', //结算组织配置-编辑
        list: '/finance/baseSettlementOrgTemporaryLog/listByAccount', //结算组织临时额度记录-通过结算组织分页列表查询
      },
    }
  },

  computed: {
    formDisabled() {
      return this.disabled
    },
    endtime() {
      const days = parseInt(this.model.temporaryDayNum)
      const time = this.model.beginTime? moment(this.model.beginTime).add(days, 'days').format('YYYY-MM-DD HH:mm:ss') : ''
      return time
    },
    model2() {
      return JSON.parse(JSON.stringify(this.model))
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    moment,
    add() {
      // this.edit(this.modelDefault);
      this.model = Object.assign({}, this.modelDefault)
      this.visible = true
    },
    edit(record) {
      // this.model = Object.assign({}, record)
      //this.model = Object.assign({}, this.modelDefault)
      this.getQueryById(record.id)
      this.visible = true
    },
    //切换临时额度
    onChangeOpenTemporary(checked) {
      //  0:关，1开   0否  1是
      this.modelObj.izOpenTemporary = checked == true ? '1' : '0'
      if (checked == false) {
        this.closeTemporary()
      }
    },
    //切换临时额度循环开关
    onChangeCycleTemporary(checked) {
      this.modelObj.izCycleTemporary = checked == true ? '1' : '0'
      this.editCycleStatusHandle()
    },
    //设置启用日期选择框禁用的日期
    disabledStartDate(current) {
      //如果初始时间小于或等于当前时间，设置禁选日期
      // if (this.initBeginTime) {
      //   if (moment(this.initBeginTime) < moment() || moment(this.initBeginTime) == moment()) {
      //     return current < moment(this.initBeginTime).subtract(1, 'days').endOf('day')
      //   } else {
      //     return current < moment().subtract(1, 'days').endOf('day')
      //   }
      // } else {
      //   return current < moment().subtract(1, 'days').endOf('day')
      // }
      return current < moment().subtract(1, 'days').endOf('day')
    },
    //验证选择的时间  计算时间差
    validateBeginTime(rule, value, callback) {
      if (value) {
        let timeDiff = 0
        // 计算两个时间相差分钟数
        ////选择时间大于当前系统时间3分钟
        if (moment(value) > moment()) {
          timeDiff = moment(value).diff(moment(), 'minute')
        }
        if (timeDiff < 4) {
          callback('临近时间节点太近，请重新选择开始时间')
        } else {
          callback()
        }
      }
    },
    //验证输入的临时额度金额
    validateTemporaryMoney(rule, value, callback) {    
      if (value < 0 || value == 0) {      
        callback('临时额度金额不能小于等于0')
      } else {
        callback()
      }
    },
    //获取结算组织配置信息
    getQueryById(id) {
      const that = this
      getAction(that.url.queryById, { id: id }).then((res) => {
        if (res.success) {
          res.result.temporaryDayNum = res.result.temporaryDayNum ? parseInt(res.result.temporaryDayNum) : null
          //that.model = res.result
          that.modelObj.izOpenTemporary = res.result.izOpenTemporary
          that.modelObj.izCycleTemporary = res.result.izCycleTemporary
          that.model.id = res.result.id
          that.model.temporaryType =res.result.temporaryType ? res.result.temporaryType : 1
          that.model.temporaryDayNum = res.result.temporaryDayNum
          that.model.temporaryBalance = res.result.temporaryBalance ? parseInt(res.result.temporaryBalance) : null
          that.model.beginTime = res.result.beginTime
          that.initBeginTime = res.result.beginTime
          if (res.result.beginTime) {          
            if (moment(res.result.beginTime) < moment() && moment() < moment(that.endtime)) {
              that.disabledOperation = true
            } else {
              that.disabledOperation = false
            }
          } else {            
            that.disabledOperation = false
          }
          that.oldModel = Object.assign({}, that.model)
          this.loadRecordData(1)
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    //设置禁止选择的时分秒
    //  disabledDateTime(){
    //    let startTime = this.initBeginTime
    //    //获取初始开始时间的分钟 和秒
    //    const disableHour=startTime?(moment(startTime).hour()):(moment().hour())
    //    const disableMinute=startTime?(moment(startTime).minute()):(moment().minute())
    //    const endMinute=Number(disableMinute)+4
    //    //如若选择的日期大于初始天，小时，分钟的禁止日期为空
    //    //如若选择的小时大于初始小时，分钟的禁止日期为空
    //    const currentHour=this.model.beginTime?(moment(this.model.beginTime).hour()):(moment().hour())
    //    if(currentHour>disableHour){
    //       return {
    //         disabledHours: () => this.range(0, disableHour),
    //       }
    //    }else{
    //       return {
    //       disabledHours: () => this.range(0, disableHour),
    //       disabledMinutes: () => this.range(0, endMinute),
    //     };
    //    }
    //  },
    //选择开始时间
    beginTimeChange(value) {},

    //编辑循环状态
    editCycleStatusHandle() {
      const config = {
        id: this.model.id,
        izCycleTemporary: this.modelObj.izCycleTemporary,
      }
      httpAction(this.url.editCycleStatus, config, 'put').then((res) => {
        if (res.success) {
          this.$message.success(res.message)
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    //结算组织配置-编辑
    saveSettlementOrgConfig() {
      const that = this
      // 触发表单验证
      that.$refs.form.validate((valid) => {
        if (valid) {
          that.saveLoading = true
          const config = {
            id: that.model.id,
            izOpenTemporary: that.modelObj.izOpenTemporary,
            temporaryDayNum: that.model.temporaryDayNum,
            beginTime: that.model.beginTime,
            temporaryType: that.model.temporaryType, 
            temporaryBalance:that.model.temporaryType=='2'? that.model.temporaryBalance :null
          }
          httpAction(that.url.edit, config, 'put')
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadRecordData(1)
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.saveLoading = false
            })
        }
      })
    },
    //关闭临时额度
    closeTemporary() {
      const that = this
      const confijLoop = {
        id: that.model.id,
        izOpenTemporary: that.modelObj.izOpenTemporary,
      }
      httpAction(that.url.edit, confijLoop, 'put')
        .then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.loadRecordData(1)
            that.resetData()
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.saveLoading = false
        })
    },
    //重置
    resetData() { 
      const that=this
      that.disabledOperation = false
      //that.disabledConfig = true    
      that.modelObj.izCycleTemporary = 0 //关闭临时额度时将循环状态也关闭
      that.model.temporaryDayNum = 0
      that.model.beginTime = ''  
      that.model.temporaryType = 1
      that.model.temporaryBalance=0
    },
    //保存
    submitForm() {
      const that = this
      that.$emit('ok')
    },
    // cancel(){
    //    const that = this
    //   if(JSON.stringify(that.oldModel) !== JSON.stringify(that.model)){
    //       that.$emit('cancelForm',true)
    //   }else{
    //      that.$emit('cancelForm',false)
    //   }
    // },
    //获取临时额度配置记录
    loadRecordData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = {
        settlementOrgId: this.model.id,
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize,
        column: 'createTime',
        order: 'desc',
      }
      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result
            this.ipagination.total = res.result.total ? res.result.total : 0
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
  },
  //  watch: {
  //    model: {
  //      handler(value) {
  //        this.disabledConfig = JSON.stringify(this.oldModel) === JSON.stringify(value) ? true : false
  //      },
  //       deep: true,
  //   },
  //  }
  // watch: {
  //   model2: {
  //     handler(newValue, oldValue) {
  //       if (newValue && oldValue && oldValue.id) {
  //         if (this.model.temporaryType == 1) {
  //           this.disabledConfig =(newValue.temporaryDayNum == oldValue.temporaryDayNum && newValue.beginTime == oldValue.beginTime) ?true:false           
  //         } else {
  //           this.disabledConfig =(newValue.temporaryDayNum == oldValue.temporaryDayNum && newValue.temporaryBalance == oldValue.temporaryBalance && newValue.beginTime == oldValue.beginTime) ? true:false
  //         }
  //       }
  //     },
  //     deep: true,
  //   },
  // },
}
</script>
<style scoped>
/deep/.ant-form {
  padding: 0 15px;
}
/deep/.ant-col-sm-12 {
  width: 110px;
}
/deep/.ant-col-sm-7 {
  width: 110px;
}
/deep/.ant-form-item {
  margin: 10px 0;
}
/deep/.ant-radio-group{
  margin: 10px 0;
}
/deep/.ant-calendar-picker{
  min-width: 213px !important;
}
/deep/.ant-col-sm-11{
  width: calc(100% - 120px);;
}
/deep/.ant-input-number{
  width: 213px !important;
}
</style>